package com.lzb.watermarkcamera;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lzb.watermarkcamera.activity.AlbumActivity;
import com.lzb.watermarkcamera.activity.EditCommonWatermarkActivity;
import com.lzb.watermarkcamera.activity.EditCustomWatermarkActivity;
import com.lzb.watermarkcamera.activity.SettingActivity;
import com.lzb.watermarkcamera.basic.media.AudioPlayerImpl;
import com.lzb.watermarkcamera.basic.media.IAudioPlayer;
import com.lzb.watermarkcamera.basic.utils.DensityUtil;
import com.lzb.watermarkcamera.basic.utils.FileP2pUtil;
import com.lzb.watermarkcamera.basic.utils.FileUtil;
import com.lzb.watermarkcamera.basic.utils.MediaUtil;
import com.lzb.watermarkcamera.basic.utils.SPUtil;
import com.lzb.watermarkcamera.basic.utils.WorkPathUtil;
import com.bumptech.glide.Glide;
import com.lzb.watermarkcamera.bean.ColorBean;
import com.lzb.watermarkcamera.bean.DelayBean;
import com.lzb.watermarkcamera.bean.Hours24Bean;
import com.lzb.watermarkcamera.bean.PersonalCardBean;
import com.lzb.watermarkcamera.bean.ResolutionBean;
import com.lzb.watermarkcamera.bean.ScaleBean;
import com.lzb.watermarkcamera.bean.WatermarkBean;
import com.lzb.watermarkcamera.databinding.ActivityHomeBinding;
import com.lzb.watermarkcamera.dialog.DelayDialog;
import com.lzb.watermarkcamera.dialog.PermissionExplainDialog;
import com.lzb.watermarkcamera.dialog.ScaleDialog;
import com.lzb.watermarkcamera.dialog.WatermarkTemplateDialog;
import com.lzb.watermarkcamera.utils.AppSpUtils;
import com.lzb.watermarkcamera.utils.CityUtils;
import com.lzb.watermarkcamera.utils.MyMediaRecorder;
import com.lzb.watermarkcamera.utils.OkhttpUtils;
import com.lzb.watermarkcamera.view.RoundedLinearLayout;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;
import com.otaliastudios.cameraview.size.AspectRatio;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;

public class HomeActivity extends BaseAc<ActivityHomeBinding> implements View.OnClickListener, SensorEventListener {

    //相机设置
    private boolean isFlash = false;//判断是否打开闪光灯
    private int shotTime = 0;//拍摄延迟
    private float myBrightness = 1;//亮度
    private CameraOptions mCameraOptions;
    private int number;//拍照倒计时
    private Handler mHandler;
    private int mRecordTime;//拍摄视频的时间
    private boolean isShoot = false;
    private boolean isStart = false;
    private ScaleDialog scaleDialog;
    private DelayDialog delayDialog;

    // 放大倍数相关
    private float currentZoom = 0f; // 当前放大倍数
    private static final float ZOOM_1X = 0f;
    private static final float ZOOM_2X = 0.1f;
    private static final float ZOOM_6X = 0.3f;

    // 参考线相关
    private boolean isReferenceLineOpen = false; // 是否开启参考线
    // 自拍镜像相关
    private boolean isSelfieMirrorOpen = false; // 是否开启自拍镜像

    //水印相关
    private int selPosition = 3;
    private View view;
    private boolean isInitLocation;
    private SensorManager sensorManager;
    private long lastUpdateTime = 0;
    private boolean hasRecord = false;
    private MyMediaRecorder mRecorder;
    private Handler mRecordHandler;
    float volume = 10000;
    private WatermarkTemplateDialog watermarkTemplateDialog;

    private IAudioPlayer mAudioPlayer;


    private final Runnable mTaskUpdateTime = new Runnable() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void run() {
            if (!hasRecord) return;
            if (selPosition != 0) return;
            volume = mRecorder.getMaxAmplitude();  //获取声压值
            if (volume > 0 && volume < 1000000) {
                float value = 20 * (float) (Math.log10(volume));
                int val = (int) value;
                TextView tvDecibel = view.findViewById(R.id.tvDecibel);
                if (val < 30) {
                    tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text1));
                } else if (val < 60) {
                    tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text2));
                } else if (val < 90) {
                    tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text3));
                } else {
                    tvDecibel.setText(getString(R.string.decibel) + "：" + val + getString(R.string.decibel_text4));
                }
            }
            mHandler.postDelayed(this, 1000);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_home;
    }

    @Override
    protected void initView() {
        mDataBinding.ivGetPermission.setOnClickListener(this);
        mDataBinding.ivSetting.setOnClickListener(this);
        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.ivCameraScale.setOnClickListener(this);
        mDataBinding.ivCameraDelay.setOnClickListener(this);
        mDataBinding.tvMagnify1.setOnClickListener(this);
        mDataBinding.tvMagnify2.setOnClickListener(this);
        mDataBinding.tvMagnify3.setOnClickListener(this);
        mDataBinding.tvPictureEdit.setOnClickListener(this);
        mDataBinding.tvCameraVideo.setOnClickListener(this);
        mDataBinding.tvCameraPicture.setOnClickListener(this);
        mDataBinding.tvTakePuzzle.setOnClickListener(this);
        mDataBinding.tvAlbum.setOnClickListener(this);
        mDataBinding.tvEditWatermark.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.tvCameraReversal.setOnClickListener(this);
        mDataBinding.tvWatermarkTemplate.setOnClickListener(this);

        mHandler = new Handler();

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //加速度感应器
        Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        //地磁感应器
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, magneticSensor, SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_GAME);

        mRecorder = new MyMediaRecorder();
        mAudioPlayer = new AudioPlayerImpl();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivGetPermission) {//申请权限
            getPermission();
        } else if (id == R.id.ivSetting) {//设置
            startActivity(SettingActivity.class);
        } else if (id == R.id.ivCameraScale) {//比例
            showScaleDialog();
        } else if (id == R.id.ivCameraFlash) {//闪光灯
            openFlash();
        } else if (id == R.id.ivCameraDelay) {//延时拍摄
            showDelayDialog();
        } else if (id == R.id.tvMagnify1) {//6倍放大
            setZoom(ZOOM_6X);
            updateMagnifyButtons(1);
        } else if (id == R.id.tvMagnify2) {//2倍放大
            setZoom(ZOOM_2X);
            updateMagnifyButtons(2);
        } else if (id == R.id.tvMagnify3) {//1倍放大
            setZoom(ZOOM_1X);
            updateMagnifyButtons(3);
        } else if (id == R.id.tvPictureEdit) {//照片编辑
            startActivity(AlbumActivity.class);
        } else if (id == R.id.tvCameraVideo) {//拍摄视频模式
            getRecordPermission();
        } else if (id == R.id.tvCameraPicture) {//拍摄图片模式
            isShoot = false;
            clearSelection();
            mDataBinding.tvCameraPicture.setTextColor(Color.parseColor("#000000"));
            mDataBinding.tvCameraPicture.setBackgroundResource(R.drawable.camera_mode_sel);
            mDataBinding.tvVideoNum.setVisibility(View.GONE);
            mDataBinding.cameraView.setMode(Mode.PICTURE);
        } else if (id == R.id.tvAlbum) {//编辑水印
            startActivity(AlbumActivity.class);
        } else if (id == R.id.tvEditWatermark) {//编辑水印
            if (selPosition == 0) {
                startActivity(EditCustomWatermarkActivity.class);
            } else {
                EditCommonWatermarkActivity.selPosition = selPosition;
                startActivity(EditCommonWatermarkActivity.class);
            }
        } else if (id == R.id.ivCameraStart) {//开始拍摄
            if (isStart) return;
            startShot();
        } else if (id == R.id.tvCameraReversal) {//镜头反转
            reversalLens();
        } else if (id == R.id.tvWatermarkTemplate) {//水印模板
            showWatermarkTemplateDialog();
        }
    }

    // 设置放大倍数
    private void setZoom(float zoomLevel) {
        if (mDataBinding.cameraView != null) {
            // CameraView支持通过setZoom()方法设置放大倍数
            mDataBinding.cameraView.setZoom(zoomLevel);
            currentZoom = zoomLevel;
        }
    }

    // 更新放大按钮的UI状态
    private void updateMagnifyButtons(int selectedIndex) {
        // 重置所有按钮状态
        mDataBinding.tvMagnify1.setTextColor(Color.parseColor("#999999"));
        mDataBinding.tvMagnify1.setBackgroundResource(R.drawable.magnify_bg);
        mDataBinding.tvMagnify2.setTextColor(Color.parseColor("#999999"));
        mDataBinding.tvMagnify2.setBackgroundResource(R.drawable.magnify_bg);
        mDataBinding.tvMagnify3.setTextColor(Color.parseColor("#999999"));
        mDataBinding.tvMagnify3.setBackgroundResource(R.drawable.magnify_bg);

        // 设置选中状态
        switch (selectedIndex) {
            case 1: // 6x
                mDataBinding.tvMagnify1.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvMagnify1.setBackgroundResource(R.drawable.magnify_sel);
                break;
            case 2: // 2x
                mDataBinding.tvMagnify2.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvMagnify2.setBackgroundResource(R.drawable.magnify_sel);
                break;
            case 3: // 1x
                mDataBinding.tvMagnify3.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvMagnify3.setBackgroundResource(R.drawable.magnify_sel);
                break;
        }
    }

    @Override
    protected void initData() {
        boolean hasPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED;
        if (hasPermission) {
            getPermission();
        } else {
            mDataBinding.llGetPermission.setVisibility(View.VISIBLE);
        }

        List<WatermarkBean> listSp = AppSpUtils.getWatermarkList();
        if (listSp == null) {
            initWatermark();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        boolean hasRecordAudioPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO)
                == PackageManager.PERMISSION_GRANTED;
        if (hasRecordAudioPermission && !hasRecord) {
            startTest();
        }

        ResolutionBean resolutionBean = AppSpUtils.getResolution();
        if (resolutionBean == null) {
            resolutionBean = new ResolutionBean("普通", 3264, 1836, "3264x1836，约5.72MB");
            AppSpUtils.saveResolution(resolutionBean);
        }

        // 根据获取的resolutionBean设置CameraView拍照分辨率
        if (mDataBinding != null && mDataBinding.cameraView != null) {
            setPictureResolution(resolutionBean.getWidth(), resolutionBean.getHeight());
        }

        // 根据拍照声音设置来决定是否播放声音
        mDataBinding.cameraView.setPlaySounds(SPUtil.getBoolean(mContext, Content.isOpenTakeSound, false));

        // 加载参考线设置状态
        isReferenceLineOpen = SPUtil.getBoolean(mContext, Content.isOpenReferenceLine, false);
        updateReferenceLineVisibility();

        // 加载自拍镜像设置状态
        isSelfieMirrorOpen = SPUtil.getBoolean(mContext, Content.isOpenSelfieMirror, false);

        setWatermarkData();

        boolean hasPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED;
        if (hasPermission) {
            isInitLocation = true;
            initLocation();
        }
    }

    private void showWatermarkTemplateDialog() {
        if (watermarkTemplateDialog == null) {
            watermarkTemplateDialog = new WatermarkTemplateDialog(mContext);
            watermarkTemplateDialog.setSelPosition(selPosition);
        }
        watermarkTemplateDialog.setListener(new WatermarkTemplateDialog.Ilistener() {
            @Override
            public void clickItem(int pos) {
                selPosition = pos;
                setWatermarkData();
            }
        });
        watermarkTemplateDialog.show();
    }

    /**
     * 更新参考线显示状态
     */
    private void updateReferenceLineVisibility() {
        if (mDataBinding != null && mDataBinding.referenceLineView != null) {
            mDataBinding.referenceLineView.setVisibility(isReferenceLineOpen ? View.VISIBLE : View.GONE);
        }
    }

    // 根据指定的宽高设置拍照分辨率
    private void setPictureResolution(int targetWidth, int targetHeight) {
        if (mDataBinding != null && mDataBinding.cameraView != null) {
            // 创建SizeSelector来选择接近目标尺寸的分辨率
            SizeSelector targetSizeSelector = SizeSelectors.and(
                    SizeSelectors.maxWidth(targetWidth),
                    SizeSelectors.maxHeight(targetHeight),
                    SizeSelectors.aspectRatio(AspectRatio.of(targetWidth, targetHeight), 0.1f)
            );

            // 设置拍照分辨率
            mDataBinding.cameraView.setPictureSize(targetSizeSelector);
        }
    }

    private void getPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_camera_permission));
        PermissionUtils.permission(Manifest.permission.CAMERA).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                mDataBinding.llGetPermission.setVisibility(View.GONE);
                //初始化相机
                initCameraView();
                setCameraPar();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    private void getRecordPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_camera_record_permission));
        PermissionUtils.permission(Manifest.permission.RECORD_AUDIO).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                isShoot = true;
                clearSelection();
                mDataBinding.tvCameraVideo.setTextColor(Color.parseColor("#000000"));
                mDataBinding.tvCameraVideo.setBackgroundResource(R.drawable.camera_mode_sel);
                mDataBinding.cameraView.setMode(Mode.VIDEO);
                mDataBinding.cameraView.setAudio(Audio.ON);
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {
                mCameraOptions = options;
            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                //获取图片 去到预览界面
                int picWidth = result.getSize().getWidth();
                int picHeight = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (picWidth * picHeight > screenWidth * screenHeight) {
                    picWidth = screenWidth;
                    picHeight = screenHeight;
                }

                // 确保水印控件已经布局完成
                ensureWatermarkLayout();

                // 获取水印控件在父容器中的实际位置（考虑拖动后的位置）
                float[] watermarkPosition = getWatermarkPosition();
                float left = watermarkPosition[0];
                float top = watermarkPosition[1];

                // 获取预览容器中水印的实际尺寸
                int watermarkWidth = mDataBinding.llWatermark.getWidth();
                int watermarkHeight = mDataBinding.llWatermark.getHeight();

                // 转换为相对于照片的比例（位置和尺寸都基于预览容器）
                float leftRate = left / mDataBinding.clCamera.getWidth();
                float topRate = top / mDataBinding.clCamera.getHeight();
                float widthRate = (float) watermarkWidth / mDataBinding.clCamera.getWidth();
                float heightRate = (float) watermarkHeight / mDataBinding.clCamera.getHeight();


                // 检查是否需要应用自拍镜像效果
                if (isSelfieMirrorOpen && mDataBinding.cameraView.getFacing() == Facing.FRONT) {
                    // 将图片转换为Bitmap并应用镜像效果
                    result.toBitmap(picWidth, picHeight, new BitmapCallback() {
                        @Override
                        public void onBitmapReady(@Nullable Bitmap bitmap) {
                            if (bitmap != null) {
                                // 应用水平镜像效果
                                Bitmap mirroredBitmap = createMirroredBitmap(bitmap);

                                Bitmap watermarkBitmap = ImageUtils.view2Bitmap(mDataBinding.llWatermark);

                                //有水印时的处理
                                Bitmap retBitmap = mirroredBitmap.copy(Bitmap.Config.ARGB_8888, true);
                                Canvas canvas = new Canvas(retBitmap);

                                // 根据照片尺寸和预览比例计算水印位置和大小
                                float left = retBitmap.getWidth() * leftRate;
                                float top = retBitmap.getHeight() * topRate;
                                int targetWidth = (int) (retBitmap.getWidth() * widthRate);
                                int targetHeight = (int) (retBitmap.getHeight() * heightRate);

                                // 缩放水印到正确的大小
                                Bitmap scaledWatermark = Bitmap.createScaledBitmap(watermarkBitmap, targetWidth, targetHeight, true);
                                canvas.drawBitmap(scaledWatermark, left, top, null);

                                // 释放缩放后的水印bitmap
                                if (scaledWatermark != watermarkBitmap && !scaledWatermark.isRecycled()) {
                                    scaledWatermark.recycle();
                                }

                                // 保存镜像后的图片
                                ImageUtils.save2Album(retBitmap, Bitmap.CompressFormat.PNG);
                                String filePath = FileUtil.generateFilePath(Content.myCamera, ".png");
                                ImageUtils.save(retBitmap, filePath, Bitmap.CompressFormat.PNG);
                                // 释放原始bitmap
                                if (bitmap != mirroredBitmap && !bitmap.isRecycled()) {
                                    bitmap.recycle();
                                }
                            }
                        }
                    });
                } else {
                    // 正常保存图片（不应用镜像）
                    result.toBitmap(picWidth, picHeight, new BitmapCallback() {
                        @Override
                        public void onBitmapReady(@Nullable Bitmap bitmap) {
                            if (bitmap != null) {
                                Bitmap watermarkBitmap = ImageUtils.view2Bitmap(mDataBinding.llWatermark);
                                //有水印时的处理
                                Bitmap retBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
                                Canvas canvas = new Canvas(retBitmap);

                                // 根据照片尺寸和预览比例计算水印位置和大小
                                float left = retBitmap.getWidth() * leftRate;
                                float top = retBitmap.getHeight() * topRate;
                                int targetWidth = (int) (retBitmap.getWidth() * widthRate);
                                int targetHeight = (int) (retBitmap.getHeight() * heightRate);

                                // 缩放水印到正确的大小
                                Bitmap scaledWatermark = Bitmap.createScaledBitmap(watermarkBitmap, targetWidth, targetHeight, true);
                                canvas.drawBitmap(scaledWatermark, left, top, null);

                                // 释放缩放后的水印bitmap
                                if (scaledWatermark != watermarkBitmap && !scaledWatermark.isRecycled()) {
                                    scaledWatermark.recycle();
                                }

                                ImageUtils.save2Album(retBitmap, Bitmap.CompressFormat.PNG);
                                String filePath = FileUtil.generateFilePath(Content.myCamera, ".png");
                                ImageUtils.save(retBitmap, filePath, Bitmap.CompressFormat.PNG);
                            }
                        }
                    });
                }
                if (selPosition == 0) {
                    boolean isAutoCount = SPUtil.getBoolean(mContext, Content.isAutoCount, false);
                    long count = SPUtil.getLong(mContext, Content.count, 1L);
                    if (isAutoCount) {
                        count++;
                        SPUtil.putLong(mContext, Content.count, count);
                    }
                    TextView tvCount = view.findViewById(R.id.tvCount);
                    tvCount.setText(getString(R.string.count) + "：" + SPUtil.getLong(mContext, Content.count, 1L));
                }
            }

            @Override
            public void onVideoRecordingStart() {
                //开始拍摄视频
                startRecordTime();
            }

            @Override
            public void onVideoRecordingEnd() {
                //视频拍摄结束
                mDataBinding.tvVideoNum.setText("00:00");
                mDataBinding.ivCameraStart.setImageResource(R.drawable.apz);
                mDataBinding.tvVideoNum.setVisibility(View.GONE);
                mDataBinding.llCameraMode.setVisibility(View.VISIBLE);
                mDataBinding.tvAlbum.setVisibility(View.VISIBLE);
                mDataBinding.tvEditWatermark.setVisibility(View.VISIBLE);
                mDataBinding.tvCameraReversal.setVisibility(View.VISIBLE);
                mDataBinding.tvWatermarkTemplate.setVisibility(View.VISIBLE);
                stopRecordTime();
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                // 确保水印控件布局完成
                ensureWatermarkLayout();

                Bitmap watermarkBitmap = ImageUtils.view2Bitmap(mDataBinding.llWatermark);

                // 获取水印实际位置和尺寸（相对于预览容器）
                float[] watermarkPosition = getWatermarkPosition();
                int watermarkWidth = mDataBinding.llWatermark.getWidth();
                int watermarkHeight = mDataBinding.llWatermark.getHeight();

                // 获取预览容器尺寸
                int previewWidth = mDataBinding.clCamera.getWidth();
                int previewHeight = mDataBinding.clCamera.getHeight();

                // 计算位置和尺寸比例（相对于预览容器）
                float leftRate = watermarkPosition[0] / previewWidth;
                float topRate = watermarkPosition[1] / previewHeight;
                float widthRate = (float) watermarkWidth / previewWidth;
                float heightRate = (float) watermarkHeight / previewHeight;

                // 获取视频文件路径
                String url = result.getFile().getPath();

                // 获取视频第一帧
                Bitmap firstFrame = MediaUtil.getVideoFirstFrame(url);
                if (firstFrame == null) {
                    ToastUtils.showShort("无法获取视频帧");
                    return;
                }

                // 根据视频第一帧的实际尺寸计算水印位置和尺寸
                double targetLeft = leftRate * firstFrame.getWidth();
                double targetTop = topRate * firstFrame.getHeight();
                double targetWidth = widthRate * firstFrame.getWidth();
                double targetHeight = heightRate * firstFrame.getHeight();

                // 保存水印图片到临时文件
                String imagePath = FileUtil.generateFilePath(Content.Temp, ".png");
                ImageUtils.save(watermarkBitmap, imagePath, Bitmap.CompressFormat.PNG);

                // 生成输出视频文件路径
                String watermarkVideoPath = FileUtil.generateFilePath(Content.Temp, ".mp4");

                String strCommand = "ffmpeg -y -i " + url + " -i " + imagePath + " -filter_complex [1:v]scale=" + targetWidth + ":" + targetHeight + "[wm];[0:v][wm]overlay=" + targetLeft + ":" + targetTop + " -preset superfast " + watermarkVideoPath;
                String[] commands = strCommand.split(" ");

                //开始执行FFmpeg命令
                RxFFmpegInvoke.getInstance()
                        .runCommandRxJava(commands)
                        .subscribe(new RxFFmpegSubscriber() {
                            @Override
                            public void onFinish() {
                                ToastUtils.showShort("视频水印添加完成");
                                // 保存到相册
                                FileP2pUtil.copyPrivateVideoToPublic(mContext, watermarkVideoPath);
                            }

                            @Override
                            public void onProgress(int progress, long progressTime) {
                                // 可以显示进度
                            }

                            @Override
                            public void onCancel() {
                                ToastUtils.showShort("视频处理已取消");
                            }

                            @Override
                            public void onError(String message) {
                                ToastUtils.showShort("视频处理失败: " + message);
                            }
                        });
                //保存到相册
//                FileP2pUtil.copyPrivateVideoToPublic(mContext, result.getFile().getPath());
            }
        });

        // 初始化放大倍数为1x
        setZoom(ZOOM_1X);
        updateMagnifyButtons(3);
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
        }
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.asgdk);
            shotTipText(getString(R.string.flash_close));
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.asgdg);
            shotTipText(getString(R.string.flash_open));
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }

    //显示提示文字
    private void shotTipText(String text) {
        mDataBinding.tvCameraTipText.setText(text);
        mDataBinding.tvCameraTipText.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mDataBinding.tvCameraTipText.setVisibility(View.GONE);
            }
        }, 500);
    }

    private void showScaleDialog() {
        if (scaleDialog == null) scaleDialog = new ScaleDialog(mContext);
        BasePopupView basePopupView = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .offsetX(0)//x轴偏移
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivCameraScale).hasShadowBg(false) // 去掉半透明背景
                .asCustom(scaleDialog);
        scaleDialog.setListener(new ScaleDialog.Ilistener() {

            @Override
            public void click(ScaleBean scaleBean) {
                ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) mDataBinding.cameraView.getLayoutParams();
                params.dimensionRatio = scaleBean.getScale(); // 直接赋值比例字符串
                mDataBinding.cameraView.setLayoutParams(params);
                mDataBinding.ivCameraScale.setImageResource(scaleBean.getImg());
            }
        });
        basePopupView.show();
    }

    private void showDelayDialog() {
        if (delayDialog == null) delayDialog = new DelayDialog(mContext);
        BasePopupView basePopupView = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .offsetX(0)//x轴偏移
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivCameraDelay).hasShadowBg(false) // 去掉半透明背景
                .asCustom(delayDialog);
        delayDialog.setListener(new DelayDialog.Ilistener() {

            @Override
            public void click(DelayBean delayBean) {
                if (delayBean.getPosition() == 0) {
                    shotTime = 0;
                    shotTipText(getString(R.string.delay_close));
                } else {
                    shotTime = delayBean.getPosition() * 5 * 1000;
                    if (delayBean.getPosition() == 1) {
                        shotTipText(getString(R.string.delay_open_text1));
                    } else {
                        shotTipText(getString(R.string.delay_open_text2));
                    }
                }
                mDataBinding.ivCameraDelay.setImageResource(delayBean.getImg());
                SPUtil.putInt(mContext, Content.isDelay, delayBean.getPosition());
            }
        });
        basePopupView.show();
    }

    //开始拍摄
    private void startShot() {
        if (!isShoot) {//照片拍摄
            if (mDataBinding.cameraView.isTakingPicture()) return;
            isStart = true;
            //加个拍照延迟
            if (shotTime > 0) {
                delayNumber();//倒计时
            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isStart = false;
                    // 根据拍照声音设置来决定是否播放声音
//                    if (SPUtil.getBoolean(mContext, Content.isOpenTakeSound, false)) {
//                        mDataBinding.cameraView.takePictureSnapshot();
//                        Uri uri = Uri.parse("android.resource://" + AppUtils.getAppPackageName() + "/" + R.raw.paizhao);
//                        mAudioPlayer.play(UriUtils.uri2File(uri).getPath());
//                    } else {
                    // 如果关闭声音，使用静音拍照方式
//                    }
                    mDataBinding.cameraView.takePicture();
                }
            }, shotTime);
        } else {//视频拍摄
            if (mDataBinding.cameraView.isTakingVideo()) {
                mDataBinding.cameraView.stopVideo();
            } else {
                isStart = true;
                //加个拍照延迟
                if (shotTime > 0) {
                    delayNumber();//倒计时
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isStart = false;
                        mDataBinding.llCameraMode.setVisibility(View.GONE);
                        mDataBinding.tvAlbum.setVisibility(View.GONE);
                        mDataBinding.tvEditWatermark.setVisibility(View.GONE);
                        mDataBinding.tvCameraReversal.setVisibility(View.GONE);
                        mDataBinding.tvWatermarkTemplate.setVisibility(View.GONE);
                        mDataBinding.tvVideoNum.setVisibility(View.VISIBLE);
                        mDataBinding.tvVideoNum.setText("00:00");
                        String filePath = WorkPathUtil.generateVideoFilePath(null);
                        if (filePath != null) {
                            mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                        }
                    }
                }, shotTime);
            }
        }
    }

    //倒计时
    private void delayNumber() {
        number = shotTime / 1000;
        new CountDownTimer(shotTime, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mDataBinding.tvCameraDelayText.setVisibility(View.VISIBLE);
                //millisUntilFinished / 1000 会有不可描述的问题
                mDataBinding.tvCameraDelayText.setText("" + number--);
            }

            @Override
            public void onFinish() {
                mDataBinding.tvCameraDelayText.setVisibility(View.GONE);
            }
        }.start();
    }

    //回显相机设置
    private void setCameraPar() {
        if (SPUtil.getInt(mContext, Content.isDelay, 0) == 0) {
            shotTime = 0;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.adjs);
        } else if ((SPUtil.getInt(mContext, Content.isDelay, 0) == 1)) {
            shotTime = 3000;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.ays5s);
        } else if ((SPUtil.getInt(mContext, Content.isDelay, 0) == 2)) {
            shotTime = 5000;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.ays10s);
        }
    }

    //开始拍摄视频
    private void startRecordTime() {
        mRecordTime = 0;
        mDataBinding.ivCameraStart.setImageResource(R.drawable.atzlz);
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
        mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
    }

    //结束拍摄视频
    private void stopRecordTime() {
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
    }

    private final Runnable mUpdateRecordTimeTask = new Runnable() {
        @Override
        public void run() {
            mRecordTime++;
            mDataBinding.tvVideoNum.setText(TimeUtils.millis2String(mRecordTime * 1000L, "mm:ss"));
            mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
        }
    };

    private void clearSelection() {
        mDataBinding.tvCameraVideo.setTextColor(Color.parseColor("#FFFFFF"));
        mDataBinding.tvCameraVideo.setBackgroundResource(0);
        mDataBinding.tvCameraPicture.setTextColor(Color.parseColor("#FFFFFF"));
        mDataBinding.tvCameraPicture.setBackgroundResource(0);
        mDataBinding.tvTakePuzzle.setTextColor(Color.parseColor("#FFFFFF"));
        mDataBinding.tvTakePuzzle.setBackgroundResource(0);
        mDataBinding.llCameraMode.setVisibility(View.VISIBLE);
        mDataBinding.tvAlbum.setVisibility(View.VISIBLE);
        mDataBinding.tvEditWatermark.setVisibility(View.VISIBLE);
        mDataBinding.tvCameraReversal.setVisibility(View.VISIBLE);
        mDataBinding.tvWatermarkTemplate.setVisibility(View.VISIBLE);
    }

    /**
     * 创建水平镜像的Bitmap
     */
    private Bitmap createMirroredBitmap(Bitmap original) {
        if (original == null) {
            return null;
        }

        // 创建一个新的Bitmap，尺寸与原始图片相同
        Bitmap mirroredBitmap = Bitmap.createBitmap(
                original.getWidth(),
                original.getHeight(),
                Bitmap.Config.ARGB_8888
        );

        // 使用Matrix进行水平翻转
        android.graphics.Matrix matrix = new android.graphics.Matrix();
        matrix.setScale(-1, 1); // 水平翻转
        matrix.postTranslate(original.getWidth(), 0); // 调整位置

        // 使用Canvas绘制镜像后的图片
        android.graphics.Canvas canvas = new android.graphics.Canvas(mirroredBitmap);
        canvas.drawBitmap(original, matrix, null);

        return mirroredBitmap;
    }

    private void initWatermark() {
        WatermarkBean watermarkBean1 = new WatermarkBean();
        watermarkBean1.setImg(R.drawable.sy1);
        watermarkBean1.setCustom(true);
        WatermarkBean.CustomBean customBean = new WatermarkBean.CustomBean();
        customBean.setOpenWaterVerification(true);
        customBean.setOpenTime(true);
        customBean.setOpenLocation(true);
        customBean.setOpenLongitudeAndLatitude(true);
        watermarkBean1.setCustomBean(customBean);

        WatermarkBean watermarkBean2 = new WatermarkBean();
        watermarkBean2.setImg(R.drawable.sy2);
        watermarkBean2.setCustom(false);
        WatermarkBean.CommonBean commonBean1 = new WatermarkBean.CommonBean();
        commonBean1.setTheme(getString(R.string.theme_text1));
        commonBean1.setThemeColor("#00C497");
        watermarkBean2.setCommonBean(commonBean1);

        WatermarkBean watermarkBean3 = new WatermarkBean();
        watermarkBean3.setImg(R.drawable.sy3);
        watermarkBean3.setCustom(false);
        WatermarkBean.CommonBean commonBean2 = new WatermarkBean.CommonBean();
        commonBean2.setTheme(getString(R.string.theme_text2));
        commonBean2.setLocation(getString(R.string.default_location));
        commonBean2.setThemeColor("#EBC527");
        watermarkBean3.setCommonBean(commonBean2);

        WatermarkBean watermarkBean4 = new WatermarkBean();
        watermarkBean4.setImg(R.drawable.sy4);
        watermarkBean4.setCustom(false);
        WatermarkBean.CommonBean commonBean3 = new WatermarkBean.CommonBean();
        commonBean3.setTheme(getString(R.string.theme_text3));
        commonBean3.setLocation(getString(R.string.default_location));
        commonBean3.setThemeColor("#FF6464");
        watermarkBean4.setCommonBean(commonBean3);

        WatermarkBean watermarkBean5 = new WatermarkBean();
        watermarkBean5.setImg(R.drawable.sy5);
        watermarkBean5.setCustom(false);
        WatermarkBean.CommonBean commonBean4 = new WatermarkBean.CommonBean();
        commonBean4.setTheme(getString(R.string.theme_text4));
        commonBean4.setLocation(getString(R.string.default_location));
        commonBean4.setThemeColor("#3D78FE");
        watermarkBean5.setCommonBean(commonBean4);

        WatermarkBean watermarkBean6 = new WatermarkBean();
        watermarkBean6.setImg(R.drawable.sy6);
        watermarkBean6.setCustom(false);
        WatermarkBean.CommonBean commonBean5 = new WatermarkBean.CommonBean();
        commonBean5.setTheme(getString(R.string.theme_text5));
        commonBean5.setLocation(getString(R.string.default_location));
        commonBean5.setThemeColor("#000000");
        watermarkBean6.setCommonBean(commonBean5);

        WatermarkBean watermarkBean7 = new WatermarkBean();
        watermarkBean7.setImg(R.drawable.sy7);
        watermarkBean7.setCustom(false);
        WatermarkBean.CommonBean commonBean6 = new WatermarkBean.CommonBean();
        commonBean6.setLocation(getString(R.string.default_location));
        watermarkBean7.setCommonBean(commonBean6);

        WatermarkBean watermarkBean8 = new WatermarkBean();
        watermarkBean8.setImg(R.drawable.sy8);
        watermarkBean8.setCustom(false);
        WatermarkBean.CommonBean commonBean7 = new WatermarkBean.CommonBean();
        commonBean7.setLocation(getString(R.string.default_location));
        watermarkBean8.setCommonBean(commonBean7);

        List<WatermarkBean> listSave = new ArrayList<>();
        listSave.add(watermarkBean1);
        listSave.add(watermarkBean2);
        listSave.add(watermarkBean3);
        listSave.add(watermarkBean4);
        listSave.add(watermarkBean5);
        listSave.add(watermarkBean6);
        listSave.add(watermarkBean7);
        listSave.add(watermarkBean8);

        AppSpUtils.saveWatermarkList(listSave);
    }

    private void setWatermarkData() {
        mDataBinding.llWatermark.removeAllViews();

        WatermarkBean watermarkBean = AppSpUtils.getWatermarkList().get(selPosition);

        if (selPosition == 0) {
            view = LayoutInflater.from(this).inflate(R.layout.layout_custom_watermark, null, false);

            LinearLayout llCard = view.findViewById(R.id.llCard);
            ImageView ivCardImg = view.findViewById(R.id.ivCardImg);
            TextView tvCardName = view.findViewById(R.id.tvCardName);
            TextView tvCardPhone = view.findViewById(R.id.tvCardPhone);
            ImageView ivLogo = view.findViewById(R.id.ivLogo);
            TextView tvCustomText = view.findViewById(R.id.tvCustomText);
            TextView tvNumber = view.findViewById(R.id.tvNumber);
            TextView tvCount = view.findViewById(R.id.tvCount);
            TextView tvTime = view.findViewById(R.id.tvTime);
            TextView tvWeather = view.findViewById(R.id.tvWeather);
            TextView tvLocation = view.findViewById(R.id.tvLocation);
            TextView tvElevation = view.findViewById(R.id.tvElevation);
            TextView tvAzimuth = view.findViewById(R.id.tvAzimuth);
            TextView tvSpeed = view.findViewById(R.id.tvSpeed);
            TextView tvLongitudeAndLatitude = view.findViewById(R.id.tvLongitudeAndLatitude);
            TextView tvDecibel = view.findViewById(R.id.tvDecibel);
            TextView tvPhotographer = view.findViewById(R.id.tvPhotographer);
            TextView tvCustomContent = view.findViewById(R.id.tvCustomContent);
            TextView tvWatermarkVerification = view.findViewById(R.id.tvWatermarkVerification);

            WatermarkBean.CustomBean customBean = watermarkBean.getCustomBean();

            // 水印验证
            if (customBean.isOpenWaterVerification()) {
                tvWatermarkVerification.setVisibility(View.VISIBLE);
            } else {
                tvWatermarkVerification.setVisibility(View.GONE);
            }

            // Logo
            if (customBean.isOpenLogo()) {
                Glide.with(this).load(customBean.getLogoPath()).into(ivLogo);
                ivLogo.setVisibility(View.VISIBLE);
            } else {
                ivLogo.setVisibility(View.GONE);
            }

            // 个人名片
            if (customBean.isOpenPersonalCard()) {
                llCard.setVisibility(View.VISIBLE);
                PersonalCardBean personalCardBean = AppSpUtils.getPersonalCard();
                Glide.with(this).load(personalCardBean.getImgPath()).into(ivCardImg);
                tvCardName.setText(personalCardBean.getName());
                tvCardPhone.setText(personalCardBean.getPhoneNumber());
            } else {
                llCard.setVisibility(View.GONE);
            }

            // 自定义文字
            if (customBean.isOpenCustomText()) {
                tvCustomText.setVisibility(View.VISIBLE);
                tvCustomText.setText(customBean.getText());
            } else {
                tvCustomText.setVisibility(View.GONE);
            }

            // 编号
            if (customBean.isOpenNumber()) {
                tvNumber.setVisibility(View.VISIBLE);
                String number = customBean.getNumber();
                if (TextUtils.isEmpty(number)) {
                    long mills = TimeUtils.getNowMills() / 1000;
                    String millsStr = String.valueOf(mills);
                    if (millsStr.length() == 10) {
                        String part1 = millsStr.substring(0, 3);
                        String part2 = millsStr.substring(3, 6);
                        String part3 = millsStr.substring(6, 10);
                        String formattedNumber = part1 + "-" + part2 + "-" + part3;
                        tvNumber.setText(getString(R.string.number) + "：" + formattedNumber);
                    }
                } else {
                    tvNumber.setText(getString(R.string.number) + "：" + number);
                }
            } else {
                tvNumber.setVisibility(View.GONE);
            }

            // 计数
            if (customBean.isOpenCount()) {
                tvCount.setVisibility(View.VISIBLE);
                tvCount.setText(getString(R.string.count) + "：" + SPUtil.getLong(this, Content.count, 1L));
            } else {
                tvCount.setVisibility(View.GONE);
            }

            // 时间
            if (customBean.isOpenTime()) {
                tvTime.setVisibility(View.VISIBLE);
                tvTime.setText(getString(R.string.time) + "：" + AppConfig.DATE + " " + AppConfig.TIME);
            } else {
                tvTime.setVisibility(View.GONE);
            }

            // 天气
            if (customBean.isOpenWeather()) {
                tvWeather.setVisibility(View.VISIBLE);
            } else {
                tvWeather.setVisibility(View.GONE);
            }

            // 位置
            if (customBean.isOpenLocation()) {
                tvLocation.setVisibility(View.VISIBLE);
            } else {
                tvLocation.setVisibility(View.GONE);
            }

            // 海拔
            if (customBean.isOpenElevation()) {
                tvElevation.setVisibility(View.VISIBLE);
            } else {
                tvElevation.setVisibility(View.GONE);
            }

            // 方位
            if (customBean.isOpenAzimuth()) {
                tvAzimuth.setVisibility(View.VISIBLE);
                tvAzimuth.setText(getString(R.string.azimuth) + "：0°");
            } else {
                tvAzimuth.setVisibility(View.GONE);
            }

            // 速度
            if (customBean.isOpenSpeed()) {
                tvSpeed.setVisibility(View.VISIBLE);
            } else {
                tvSpeed.setVisibility(View.GONE);
            }

            // 经纬度
            if (customBean.isOpenLongitudeAndLatitude()) {
                tvLongitudeAndLatitude.setVisibility(View.VISIBLE);
            } else {
                tvLongitudeAndLatitude.setVisibility(View.GONE);
            }

            // 分贝
            if (customBean.isOpenDecibel()) {
                tvDecibel.setVisibility(View.VISIBLE);
            } else {
                tvDecibel.setVisibility(View.GONE);
            }

            // 摄影师
            if (customBean.isOpenPhotographer()) {
                tvPhotographer.setVisibility(View.VISIBLE);
                WatermarkBean.PhotographerBean photographerBean = customBean.getPhotographerBean();
                if (photographerBean != null) {
                    tvPhotographer.setText(photographerBean.getTitle() + "：" + photographerBean.getContent());
                } else {
                    tvPhotographer.setText(getString(R.string.photographer) + "：" + getString(R.string.click_edit));
                }
            } else {
                tvPhotographer.setVisibility(View.GONE);
            }

            // 自定义内容列表
            List<String> listContent = customBean.getCustomTextList();
            if (listContent != null && !listContent.isEmpty()) {
                tvCustomContent.setVisibility(View.VISIBLE);
                String content = "";
                for (int i = 0; i < listContent.size(); i++) {
                    content += listContent.get(i);
                    if (i != listContent.size() - 1) {
                        content += '\n';
                    }
                }
                tvCustomContent.setText(content);
            } else {
                tvCustomContent.setVisibility(View.GONE);
            }

            boolean hasPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED;
            if (!hasPermission) {
                tvWeather.setText(getString(R.string.weather) + "：" + getString(R.string.not_award_permission));
                tvLocation.setText(getString(R.string.location) + "：" + getString(R.string.not_award_permission));
                tvElevation.setText(getString(R.string.elevation) + "：" + getString(R.string.not_award_permission));
                tvSpeed.setText(getString(R.string.speed) + "：" + getString(R.string.not_award_permission));
                tvLongitudeAndLatitude.setText(getString(R.string.longitude_and_latitude) + "：" + getString(R.string.not_award_permission));
            }

        } else {
            // Common 水印模板 (position 1-7)
            WatermarkBean.CommonBean commonBean = watermarkBean.getCommonBean();

            if (selPosition == 1) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark1, null, false);

                TextView tvTheme = view.findViewById(R.id.tvTheme);
                TextView tvPeople = view.findViewById(R.id.tvPeople);

                tvTheme.setText(commonBean.getTheme());
                if (commonBean.getPeople() != null) {
                    tvPeople.setText(getString(R.string.inspector) + "：" + commonBean.getPeople());
                } else {
                    tvPeople.setText(getString(R.string.inspector) + "：" + getString(R.string.click_edit_content));
                }

            } else if (selPosition == 2) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark2, null, false);

                TextView tvTheme = view.findViewById(R.id.tvTheme);
                tvTheme.setText(commonBean.getTheme());

            } else if (selPosition == 3 || selPosition == 4 || selPosition == 5) {
                if (selPosition == 3) {
                    view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark3, null, false);
                } else if (selPosition == 4) {
                    view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark4, null, false);
                } else {
                    view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark5, null, false);
                }

                TextView tvTheme = view.findViewById(R.id.tvTheme);
                tvTheme.setText(commonBean.getTheme());

            } else if (selPosition == 6) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark6, null, false);

            } else if (selPosition == 7) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark7, null, false);
            }

            // 设置公共的日期、时间、星期、位置信息
            TextView tvDate = view.findViewById(R.id.tvDate);
            TextView tvTime = view.findViewById(R.id.tvTime);
            TextView tvWeek = view.findViewById(R.id.tvWeek);
            TextView tvLocation = view.findViewById(R.id.tvLocation);

            tvDate.setText(AppConfig.DATE);
            tvTime.setText(AppConfig.TIME);
            long mill = TimeUtils.string2Millis(AppConfig.DATE, new SimpleDateFormat("yyyy-MM-dd"));
            tvWeek.setText(TimeUtils.millis2String(mill, new SimpleDateFormat("EEEE")));
            if (commonBean.getLocation() != null) {
                if (selPosition == 1) {
                    tvLocation.setText(getString(R.string.inspection_location) + "：" + commonBean.getLocation());
                } else {
                    tvLocation.setText(commonBean.getLocation());
                }
            } else {
                if (selPosition == 1) {
                    tvLocation.setText(getString(R.string.inspection_location) + "：" + getString(R.string.click_edit_content));
                } else {
                    tvLocation.setText(getString(R.string.click_edit_content));
                }
            }

            // 设置水印背景颜色（仅适用于非第6、7位置的水印模板）
            if (selPosition != 6 && selPosition != 7) {
                RoundedLinearLayout llWatermarkBg = view.findViewById(R.id.llWatermarkBg);
                if (llWatermarkBg != null) {
                    llWatermarkBg.setBackgroundColor(Color.parseColor(commonBean.getThemeColor()));
                }
            }
        }

        // 设置llWatermark的宽度与当前加载的布局文件实际宽度一致
        ViewGroup.LayoutParams watermarkParams = mDataBinding.llWatermark.getLayoutParams();

        // 根据选择的position设置对应的布局宽度，默认为match_parent
        switch (selPosition) {
            case 1:
                watermarkParams.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 229, getResources().getDisplayMetrics()
                ); // layout_common_watermark1: 229dp
                break;
            case 2:
                watermarkParams.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 230, getResources().getDisplayMetrics()
                ); // layout_common_watermark2: 230dp
                break;
            case 3:
            case 4:
            case 5:
                watermarkParams.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 240, getResources().getDisplayMetrics()
                ); // layout_common_watermark3/4/5: 240dp
                break;
            case 6:
                watermarkParams.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 240, getResources().getDisplayMetrics()
                ); // layout_common_watermark6: 240dp
                break;
            case 7:
                watermarkParams.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 240, getResources().getDisplayMetrics()
                ); // layout_common_watermark7: 240dp
                break;
            default:
                watermarkParams.width = ViewGroup.LayoutParams.MATCH_PARENT; // 默认match_parent
                break;
        }

        mDataBinding.llWatermark.setLayoutParams(watermarkParams);

        // 将水印视图添加到主布局
        mDataBinding.llWatermark.addView(view);
    }

    private LocationManager mLocationMgr; // 声明一个定位管理器对象


    private boolean isLocationEnable = false; // 定位服务是否可用

    public void initLocation() {
        mLocationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria(); // 创建一个定位准则对象
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 设置定位精确度
        criteria.setAltitudeRequired(true); // 设置是否需要海拔信息
        criteria.setBearingRequired(true); // 设置是否需要方位信息
        criteria.setCostAllowed(true); // 设置是否允许运营商收费
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 设置对电源的需求
        // 获取定位管理器的最佳定位提供者
        String bestProvider = mLocationMgr.getBestProvider(criteria, true);
        if (bestProvider != null && mLocationMgr.isProviderEnabled(bestProvider)) { // 定位提供者当前可用
            beginLocation(bestProvider); // 开始定位
            isLocationEnable = true;
        } else { // 定位提供者暂不可用
            ToastUtils.showShort(getString(R.string.please_open_location_service));
            isLocationEnable = false;
        }
    }

    private void beginLocation(String method) {

        // 检查当前设备是否已经开启了定位功能

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)

                != PackageManager.PERMISSION_GRANTED) {
            ToastUtils.showShort(getString(R.string.please_open_location_permission));
            return;

        }

        // 设置定位管理器的位置变更监听器

        mLocationMgr.requestLocationUpdates(method, 300, 0, mLocationListener);

        // 获取最后一次成功定位的位置信息

        Location location = mLocationMgr.getLastKnownLocation(method);
        if (location != null) {
            setLocation(location); // 显示定位结果文本
        }


    }
    // 定义一个位置变更监听器

    private LocationListener mLocationListener = new LocationListener() {

        @Override

        public void onLocationChanged(Location location) {
            if (location != null) {
                setLocation(location); // 显示定位结果文本
            }
        }

        @Override

        public void onProviderDisabled(String arg0) {
        }

        @Override

        public void onProviderEnabled(String arg0) {
        }

        @Override

        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        }

    };

    private void setLocation(Location location) {
        if (selPosition != 0) return;

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        // 创建DecimalFormat实例用于格式化数值
        DecimalFormat df = new DecimalFormat("#.##");

        // 获取并显示位置名称
        String locationStr = getLocationName(latitude, longitude);
        if (!TextUtils.isEmpty(locationStr)) {
            mLocationMgr.removeUpdates(mLocationListener);
        }

        TextView tvElevation = view.findViewById(R.id.tvElevation);
        TextView tvSpeed = view.findViewById(R.id.tvSpeed);
        TextView tvLongitudeAndLatitude = view.findViewById(R.id.tvLongitudeAndLatitude);

        // 显示海拔信息
        if (location.hasAltitude()) {
            double altitude = location.getAltitude();
            String altitudeStr = df.format(altitude) + "米";
            tvElevation.setText(getString(R.string.elevation) + "：" + altitudeStr);
        } else {
            String altitudeStr = "0.0米";
            tvElevation.setText(getString(R.string.elevation) + "：" + altitudeStr);
        }

        // 显示速度信息
        if (location.hasSpeed()) {
            float speed = location.getSpeed();
            int speedInt = (int) Math.round(speed * 3.6); // 转换为km/h并四舍五入为整数
            String speedStr = speedInt + " 公里/小时";
            tvSpeed.setText(getString(R.string.speed) + "：" + speedStr);
        } else {
            String speedStr = "0公里/小时";
            tvSpeed.setText(getString(R.string.speed) + "：" + speedStr);
        }

        // 显示经纬度信息
        String latStr = df.format(Math.abs(latitude)) + "°" + (latitude >= 0 ? "N" : "S");
        String lonStr = df.format(Math.abs(longitude)) + "°" + (longitude >= 0 ? "E" : "W");
        String latLonStr = latStr + ", " + lonStr;
        tvLongitudeAndLatitude.setText(getString(R.string.longitude_and_latitude) + "：" + latLonStr);
    }

    private String getLocationName(double lat, double lon) {

        TextView tvLocation = view.findViewById(R.id.tvLocation);
        // 创建DecimalFormat实例用于格式化经纬度
        DecimalFormat df = new DecimalFormat("#.#####");

        // 方案1：使用Android原生Geocoder
        if (Geocoder.isPresent()) {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
                if (!addresses.isEmpty()) {
                    Address address = addresses.get(0);
                    String location = address.getAddressLine(address.getMaxAddressLineIndex());
                    tvLocation.setText(getString(R.string.location) + "：" + location);
                    getCity24(CityUtils.getCityId(addresses.get(0).getLocality()));
                    return location;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 如果Geocoder不可用，只显示格式化的经纬度
        String latStr = df.format(Math.abs(lat)) + "°" + (lat >= 0 ? "N" : "S");
        String lonStr = df.format(Math.abs(lon)) + "°" + (lon >= 0 ? "E" : "W");
        String coordsOnly = latStr + ", " + lonStr;
        tvLocation.setText(getString(R.string.location) + "：" + coordsOnly);
        return "";
    }

    private void getCity24(String cityId) {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("cityId", cityId);
        /*   stringStringHashMap.put("token", "008d2ad9197090c5dddc76f583616606");*/
        OkhttpUtils.getInstance().postRequest("whapi/json/alicityweather/forecast24hours", stringStringHashMap, new OkhttpUtils.HttpCallBack() {
            @Override
            public void onSusscess(String data) {
                Hours24Bean cityInfoBean = new Gson().fromJson(data, Hours24Bean.class);
                if (cityInfoBean.getCode() == 0) {
                    List<Hours24Bean.DataBean.HourlyBean> hourList = cityInfoBean.getData().getHourly();
                    if (!hourList.isEmpty()) {
                        //当前气温
                        int temp = (int) hourList.get(0).getTemp();

                        TextView tvWeather = view.findViewById(R.id.tvWeather);

                        tvWeather.setText(hourList.get(0).getCondition() + " " + temp + "℃");
                    }
                }

            }

            @Override
            public void onFail(String meg) {
                Log.e("sssssss", meg);
            }
        });
    }

    float[] accelerometerValues = new float[3];

    float[] magneticValues = new float[3];

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (selPosition != 0) return;
        // 判断当前是加速度感应器还是地磁感应器
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            //赋值调用clone方法
            accelerometerValues = event.values.clone();
        } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            //赋值调用clone方法
            magneticValues = event.values.clone();
        }
        if (accelerometerValues != null && magneticValues != null) {
            long curTime = System.currentTimeMillis();
            if (curTime - lastUpdateTime < 500) return;
            lastUpdateTime = curTime;
            calculateOrientation(); // 加速度和磁场强度两个都有了，才能计算磁极的方向
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    //计算方位
    private void calculateOrientation() {
        float[] R = new float[9];
        float[] values = new float[3];
        SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticValues);
        sensorManager.getOrientation(R, values);
        //values[0]的取值范围是-180到180度。
        double value = Math.toDegrees(values[0]);
        //+-180表示正南方向，0度表示正北，-90表示正西，+90表示正东

        // 将value转换为0-360度范围
        if (value < 0) {
            value = value + 360;
        }

        String direction = "";
        if ((value >= 337.5 && value <= 360) || (value >= 0 && value < 22.5)) {
            direction = "北";
        } else if (value >= 22.5 && value < 67.5) {
            direction = "东北";
        } else if (value >= 67.5 && value < 112.5) {
            direction = "东";
        } else if (value >= 112.5 && value < 157.5) {
            direction = "东南";
        } else if (value >= 157.5 && value < 202.5) {
            direction = "南";
        } else if (value >= 202.5 && value < 247.5) {
            direction = "西南";
        } else if (value >= 247.5 && value < 292.5) {
            direction = "西";
        } else if (value >= 292.5 && value < 337.5) {
            direction = "西北";
        }

        TextView tvAzimuth = view.findViewById(com.lzb.watermarkcamera.R.id.tvAzimuth);

        // 更新UI显示方位角
        DecimalFormat df = new DecimalFormat("0");
        String azimuthText = getString(com.lzb.watermarkcamera.R.string.azimuth) + "：" + direction + " " + df.format(value) + "° ";
        tvAzimuth.setText(azimuthText);
    }

    //开始检测
    private void startTest() {
        String musicPath = FileUtil.generateFilePath(Content.Temp, ".mp3");
        try {
            mRecorder.setMyRecAudioFile(FileUtils.getFileByPath(musicPath));
            if (mRecorder.startRecorder()) {
                hasRecord = true;
                startTime();
            } else {
                ToastUtils.showShort(R.string.audio_fail_tips);
            }
        } catch (Exception e) {
            ToastUtils.showShort(R.string.audio_fail_tips2);
            e.printStackTrace();
        }
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTime();
        FileUtils.deleteFilesInDir(PathUtils.getFilesPathExternalFirst() + Content.Temp);
    }

    // 获取水印控件在父容器中的实际位置
    private float[] getWatermarkPosition() {
        // DraggableViewHome 的 getX() 和 getY() 返回的就是相对于父容器的位置
        float x = mDataBinding.llWatermark.getX();
        float y = mDataBinding.llWatermark.getY();

        return new float[]{x, y};
    }

    // 确保水印控件已经布局完成，获取准确的尺寸信息
    private void ensureWatermarkLayout() {
        if (mDataBinding.llWatermark.getWidth() == 0 || mDataBinding.llWatermark.getHeight() == 0) {
            // 强制测量水印控件
            mDataBinding.llWatermark.measure(
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            );
        }
    }

}